<?php

/**
 *
 * @author owenzhang
 * @time   2020-10-22
 */

namespace app\traits;

use JetBrains\PhpStorm\Pure;

trait ModelTrait
{

    #[Pure] final public static function getTableName(): string
    {
        return (new self())->getName();
    }

    final public static function getOne($where, $field = '', $expire = 1, $order = 'id desc'): array
    {
        return self::where($where)->field($field)->orderRaw($order)->cache(true, $expire)->findOrEmpty()->toArray();
    }

    final public static function getField($where, $field, $expire = 1, $default = null): int|string
    {
        $value = self::where($where)->cache(true, $expire)->value($field, $default);
        return $value ?: 0;
    }

    final public static function getFieldByOrder($where, $field, $order = '', $expire = 1, $default = null): int|string
    {
        $value = self::where($where)->orderRaw($order)->cache(true, $expire)->value($field, $default);
        return $value ?: 0;
    }

    public static function getCount($where, $expire = 1): int
    {
        return self::where($where)->cache(true, $expire)->count();
    }

    final public static function getAllList($where, $field = 'id', $order = 'id desc', $expire = 1): array
    {
        return self::where($where)->field($field)->orderRaw($order)->cache(true, $expire)->select()->toArray();
    }

    final public static function getList($where, $field = 'id', $order = 'id desc', $page = 1, $listRows = 20, $expire = 1): array
    {
        return self::where($where)->field($field)->orderRaw($order)->page($page, $listRows)->cache(true, $expire)->select()->toArray();
    }

    final public static function getColumn($where, $field = 'id', $order = 'id desc', $key = '', $page = 1, $listRows = 20, $expire = 1): array
    {
        return self::where($where)->order($order)->page($page, $listRows)->cache(true, $expire)->column($field, $key);
    }

    final public static function getAllColumn($where, $field = 'id', $order = 'id desc', $key = '', $expire = 1): array
    {
        return self::where($where)->order($order)->cache(true, $expire)->column($field, $key);
    }

    final public static function updateDataCache($where, $data): int
    {
        return self::where($where)->cache(true)->update($data);
    }

    final public static function deleteData($where): int
    {
        return self::where($where)->delete();
    }
}
